﻿/// <reference path="vswd-ext_2.2.js" />

/*****************************************************

* Create Date : 2009-12-11
* Description: this file is use for create status panel component

*****************************************************/
var txtname = new Ext.form.TextField({
    id: 'txtname',
    fieldLabel: _TrackerMain_TrackerName,
    labelStyle: 'padding-top:3px;padding-left:20px',
    width: 100,
    readOnly: true
});

var txtgpstime = new Ext.form.TextField({
    id: 'txtgpstime',
    fieldLabel: _TrackerMain_GPSTime,
    labelStyle: 'padding-top:3px;padding-left:20px',
    width: 100,
    readOnly: true
});

var txtreceivedtime = new Ext.form.TextField({
    id: 'txtreceivedtime',
    fieldLabel: _TrackerMain_ReceivedTime,
    labelStyle: 'padding-top:3px;padding-left:20px',
    width: 100,
    readOnly: true
});

var txtgpsvalid = new Ext.form.TextField({
    id: 'txtgpsvalid',
    fieldLabel: _TrackerMain_GPSValid,
    labelStyle: 'padding-top:3px;padding-left:20px',
    width: 100,
    readOnly: true
});

var txtlatitude = new Ext.form.TextField({
    id: 'txtlatitude',
    fieldLabel: _TrackerMain_Latitude,
    labelStyle: 'padding-top:3px;padding-left:20px',
    width: 100,
    readOnly: true
});

var txtlongitude = new Ext.form.TextField({
    id: 'txtlongitude',
    fieldLabel: _TrackerMain_Longitude,
    labelStyle: 'padding-top:3px;padding-left:20px',
    width: 100,
    readOnly: true
});

var txtspeed = new Ext.form.TextField({
    id: 'txtspeed',
    fieldLabel: showmiles ? _TrackerMain_Speed + "(" + _TrackerMain_MPH + ")" : _TrackerMain_Speed,
    labelStyle: 'padding-top:3px;padding-left:20px',
    width: 70,
    readOnly: true
});

var txtdirection = new Ext.form.TextField({
    id: 'txtdirection',
    fieldLabel: _TrackerMain_Direction,
    labelStyle: 'padding-top:3px;padding-left:18px',
    width: 70,
    readOnly: true
});

var txtaltitude = new Ext.form.TextField({
    id: 'txtaltitude',
    fieldLabel: _TrackerMain_Altitude,
    labelStyle: 'padding-top:3px;padding-left:20px',
    width: 100,
    readOnly: true
});

var txtjourney = new Ext.form.TextField({
    fieldLabel: showmiles ? _TrackerMain_JourneyMiles : _TrackerMain_JouneryKM,
    labelStyle: 'padding-top:3px;padding-left:20px',
    width: 100,
    readOnly: true
});

var txtruntime = new Ext.form.TextField({
    fieldLabel: _TrackerMain_RunTime,
    labelStyle: 'padding-top:3px;padding-left:20px',
    width: 100,
    readOnly: true
});

var userDefineData = [];
var userdefinestore = new Ext.data.ArrayStore({
    // store configs
    autoDestroy: true,
    data: userDefineData,
    storeId: 'myStore',
    // reader configs
    idIndex: 0,
    fields: [
       'propertyname',
       'propertyvalue'
       ]
});



/*var grdOther = new Ext.list.ListView({
//hideHeaders:true,
store: userdefinestore,
emptyText :"",
border:true,
//fieldLabel: _TrackerMain_Others,
//labelStyle: 'padding-top:3px;padding-left:20px',
//style: 'padding-top:6px;padding-left:30px',
height:70,
width :230,
//reserveScrollOffset: true,
columns: [{
header: _NewForText_PropertyName,
width: .5,
dataIndex: 'propertyname'
}, {
header: _NewForText_ValueText,
width: .5,
dataIndex: 'propertyvalue'
}]
});*/

var grdOther = new Ext.grid.GridPanel({
    //hideHeaders:true,
    store: userdefinestore,
    emptyText: "",
    border: true,
    //fieldLabel: _TrackerMain_Others,
    //labelStyle: 'padding-top:3px;padding-left:20px',
    //style: 'padding-top:6px;padding-left:30px',
    height: 120,
    width: 230,
    //reserveScrollOffset: true,
    columns: [{
        header: false,
            sortable: true,
        //width: .5,
        dataIndex: 'propertyname'
    }, {
        header: false,
        //width: .5,
        dataIndex: 'propertyvalue'
}]

    });

    var panelOthers = new Ext.Panel({
        width: 250,
        height: 120,
        fieldLabel: _TrackerMain_Others,
        labelStyle: 'padding-top:3px;padding-left:20px',
        border: false,
        //collapsible: true,
        //layout: 'form',
        //title: 'Simple ListView (0 items selected)',
        items: grdOther
    });

    var pstatuscolumn1 = new Ext.Panel({
        id: 'pstatuscolumn1',
        labelWidth: 150,
        width: 280,
        layout: 'form',
        border: false,
        bodyStyle: 'padding-top:3px',
        items: [txtname, txtgpstime, txtreceivedtime, txtjourney]
    });

    var pstatuscolumn2 = new Ext.Panel({
        id: 'pstatuscolumn2',
        layout: 'form',
        labelWidth: 130,
        width: 280,
        border: false,
        bodyStyle: 'padding-top:3px',
        items: [txtgpsvalid, txtlatitude, txtlongitude, txtruntime]
    });

    var txtlocation = new Ext.form.TextArea({
        id: 'txtlocation',
        fieldLabel: _TrackerMain_Location,
        labelStyle: 'padding-top:1px;padding-left:20px',
        width: 360, //680,
        height: 45,
        //autoHeight:true,
        //autoWidth:true,
        readOnly: true
    });


    var pstatusrow2 = new Ext.Panel({
        id: 'pstatusrow2',
        labelWidth: 150,
        layout: 'form',
        style: 'padding-top:0px',
        border: false,
        height: 60,
        width: 550,
        items: [txtlocation]
    });

    /**************new panel*******************/

    var pr1 = new Ext.Panel({
        layout: 'table',
        border: false,
        bodyStyle: 'padding-top:3px',
        height: 120,
        width: 780,
        layoutConfig: { columns: 2 },
        items: [pstatuscolumn1, pstatuscolumn2]
    });

    var pr2 = new Ext.Panel({
        layout: 'table',
        border: false,
        bodyStyle: 'padding-top:5px',
        height: 40,
        width: 320,
        layoutConfig: { columns: 2 },
        items: [new Ext.Panel({
            labelWidth: 60,
            width: 160,
            layout: 'form',
            border: false,
            bodyStyle: 'padding-top:3px',
            items: [txtspeed]
        }), new Ext.Panel({

            labelWidth: 60,
            width: 160,
            layout: 'form',
            border: false,
            bodyStyle: 'padding-top:3px',
            items: [txtdirection]
        })]
    });

    var pc1 = new Ext.Panel({
        layout: 'form',
        border: false,
        bodyStyle: 'padding-top:0px',
        height: 170,
        width: 550,
        //layoutConfig:{columns:2},
        items: [pr1, pstatusrow2]
    });

    var pc2 = new Ext.Panel({
        layout: 'form',
        height: 170,
        width: 450,
        border: false,
        labelWidth: 60,
        bodyStyle: 'padding-top:3px',
        items: [pr2, panelOthers]
    });


    var panelstatus = new Ext.Panel({
        id: 'panelstatus',
        title: _TrackerMain_Status,
        iconCls: 'icon-information',
        layout: 'table',
        layoutConfig: { columns: 2 },
        //items: [pstatusrow1,pstatusrow2]
        items: [pc1, pc2]
    });

    var immealarmstore = new Ext.data.ArrayStore({
        fields: ["sssid", "trackername", "gpstime", "location", "latitude", "longitude", "alarmexpression", "alarmtime","alarmspeed"],
        data: []
    });

    var panelalarms = new Ext.grid.GridPanel({
        store: immealarmstore,
        columns: [
                    { header: _Alarm_Header_Name, width: 75, sortable: true, menuDisabled: true, dataIndex: 'trackername' },
                    { header: _Alarm_Header_AlarmType, width: 150, sortable: true, menuDisabled: true, dataIndex: 'alarmexpression' },
                    { header: _Alarm_AlarmTime, width: 100, sortable: true, menuDisabled: true, dataIndex: 'alarmtime' },
                    { header: _Alarm_Header_Location, width: 350, sortable: true, menuDisabled: true, dataIndex: 'location' },
                    { header: _Alarm_Header_Latitude, width: 85, sortable: true, menuDisabled: true, dataIndex: 'latitude' },
                    { header: _Alarm_Header_Longitude, width: 85, sortable: true, menuDisabled: true, dataIndex: 'longitude' }
                ],
        width: 885,
        height: 300,
        autoScroll: true,
        title: _TrackerMain_Alarm,
        iconCls: 'icon-alarm'
    });

    panelalarms.addListener('render', function(grid) {
        var store = grid.getStore(), count = store.getCount(), recycleTimes = 0;  // Capture the Store.
        if (count > 0) {
            var i = 0;
            var parkingInterval = window.setInterval(function() {
                if (recycleTimes >= 10) {
                    i++;
                    recycleTimes = 0;
                }
                if (i == count) {
                    window.clearInterval(parkingInterval);

                    return;
                }

                else {
                    var record = store.getAt(i);
                    imap.geoCoder(String(record.data.location).split(',')[0], String(record.data.location).split(',')[1],
                               function(address, index) {
                                   if (address == "") {
                                       recycleTimes++;
                                       return;
                                   }
                                   record.set("location", address);
                                   i += index;
                               });
                }
            }, 1000);
        }

        var view = grid.getView();    // Capture the GridView.
        grid.tip = new Ext.ToolTip({
            target: view.mainBody,    // The overall target element.
            //delegate: '.x-grid3-row', // Each grid row causes its own seperate show and hide.   
            delegate: '.x-grid3-cell', // Each grid cell causes its own seperate show and hide.   
            trackMouse: true,         // Moving within the row should not hide the tip.   
            renderTo: document.body,  // Render immediately so that tip.body can be referenced prior to the first show.   
            listeners: {              // Change content dynamically depending on which element triggered the show.   
                beforeshow: function updateTipBody(tip) {
                    var rowIndex = view.findRowIndex(tip.triggerElement);
                    var cellIndex = view.findCellIndex(tip.triggerElement);
                    if (cellIndex == 1 || cellIndex == 3) {
                        var cell = view.getCell(rowIndex, cellIndex);
                        if (cell.innerText.length > 0) {
                            tip.body.dom.innerHTML = cell.innerText;
                            return true;
                        }
                        else
                            return false;
                    }
                    else {
                        return false;
                    }
                }
            }
        });
    });

    panelalarms.addListener('rowdblclick', function(grid, rowindex, e) {

//        var sssid = immealarmstore.getAt(rowindex).get("sssid");
//        var singlelocationstore = createSingleLocationStore(sssid);
//        singlelocationstore.load({
//            callback: function() {
//                if (imap != null) {
//                    var count = singlelocationstore.getCount();
//                    if (count > 0) {
//                        imap.drawFromStore(singlelocationstore, true);
//                        singlelocationstore.each(function(record) {
//                            showStatusinPanelByRecord(record);
//                        });
//                    }
//                    else {
//                        Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
//                        Ext.Msg.show({
//                            title: _TrackerMain_Title,
//                            msg: _Message_TrackerNoData,
//                            buttons: Ext.Msg.OK,
//                            animEl: 'elId',
//                            icon: Ext.MessageBox.INFO
//                        });
//                    }
//                }
//            }
//        });
        var record = panelalarms.getStore().getAt(rowindex);
        var name = record.get("trackername");
        //var gpsvalid = parseInt(record.get("gpsvalid"));
        var longitude = parseFloat(record.get("longitude"));
        var latitude = parseFloat(record.get("latitude"));
        //var direction = parseInt(record.get("direction"));
        var speed = parseFloat(record.get("alarmspeed"));
        //var altitude = parseInt(record.get("altitude"));
        var alarmtime = record.get("alarmtime");
        //var receivedtime = record.get("receivedtime");
        //var location = record.get("location");
        var alarm = record.get("alarmexpression");
        var alarminfo = new TrackerInfo("", name, "", true, longitude, latitude, alarmtime, alarmtime, 0, speed, 0, "", "", alarm, null);
        var win = createAlarmMapWindow(_TrackerMain_AlarmPoint + '(' + name + ',' + alarmtime + ')');
        win.show(); // 显示出来
        nextwindowx += 20;
        nextwindowy += 20;
        var rmap = createMap(win.getMap(), true, null, gmapurl);
        rmap.drawAlarmPoint(alarminfo);
    });

    function addAlarmtoImmAlarmList(sssid, trackername, gpstime, lati, longi, alarmexpression, alarmtime, alarmspeed,showaddressimme) {
        hasEmergency = true;
        if (immealarmstore.getCount() > 200)
            immealarmstore.removeAt(immealarmstore.getCount() - 1);
        var isnewalarm = true;
        var i;
        for (i = 0; i < immealarmstore.getCount(); i++) {
            var record = immealarmstore.getAt(i);
            if (record.get("trackername") == trackername && record.get("alarmexpression") == alarmexpression && record.get("alarmtime") == alarmtime) {
                isnewalarm = false;
                break;
            }
        }
        if (isnewalarm) {
            var row = new Object();
            row.sssid = sssid;
            row.trackername = trackername;
            row.gpstime = gpstime;
            row.location = "";
            row.latitude = lati;
            row.longitude = longi;
            row.alarmexpression = alarmexpression;
            row.alarmtime = alarmtime;
            row.alarmspeed = alarmspeed;
            var record = new Ext.data.Record(row)
            immealarmstore.insert(0, record);
            record.set("location", lati + "," + longi);
            if (showaddressimme) {
                if (imap != null) {
                    imap.geoCoder(lati, longi, function(address) {
                        record.set("location", address);
                    });
                }
            }
        }
    }

    var infostore = new Ext.data.ArrayStore({
        autoDestroy: true,
        data: [],
        fields: ['time', 'trackername', 'info']
    });

    //get time zone
    function gettimezone() {
        var now = new Date();
        return now.getTimezoneOffset();
    }

    function getTime() {

        var tt = getCookie("gpstimezone");
        var timezone;
        if (tt != null)
            timezone = parseInt(tt);
        else
            timezone = -gettimezone();
        var time = new Date();

        time.setMinutes(time.getMinutes() + gettimezone() + timezone);
        hours = time.getHours();
        mins = time.getMinutes();
        secs = time.getSeconds();
        if (hours < 10)
            hours = "0" + hours;
        if (mins < 10)
            mins = "0" + mins;
        if (secs < 10)
            secs = "0" + secs;
        return hours + ":" + mins + ":" + secs;
    }

    var lstInfo = new Ext.list.ListView({
        //hideHeaders:true,
        store: infostore,
        emptyText: "",
        border: true,
        //reserveScrollOffset: true,
        columns: [{
            header: _TrackerMain_Time,
            width: .2,
            dataIndex: 'time'
            }, {
                header: _TrackerMain_TrackerName,
                width: .2,
                dataIndex: 'trackername'
            }, {
                header: _TrackerMain_Info,
                dataIndex: 'info'
            }]
        });

        function addNewInfo(trackername, info) {
            if (infostore.getCount() > 200)
                infostore.removeAt(infostore.getCount() - 1);
            var row = new Object();
            row.time = getTime();
            row.trackername = trackername;
            row.info = info;
            var record = new Ext.data.Record(row)
            infostore.insert(0, record);
        }

        function addNewInfoWithTime(trackername, time, info) {
            if (infostore.getCount() > 200)
                infostore.removeAt(infostore.getCount() - 1);
            var row = new Object();
            row.time = time;
            row.trackername = trackername;
            row.info = info;
            var record = new Ext.data.Record(row)
            infostore.insert(0, record);
        }

        var panelinfo = new Ext.Panel({
            title: _TrackerMain_Info,
            layout: 'form',
            items: lstInfo,
            autoScroll: true,
            height: 300,
            iconCls: 'icon-upload'
        });

        function getMonthDayFromFullTime(value) {
			if(value == null){
				return "";
			}
            var pos1 = value.indexOf('-');
            return value.substr(pos1 + 1, value.length - pos1 - 1);
        }
        
        function showStatusinPanelByTrackerInfo(tinfo) {
            txtname.setValue(tinfo.devicename);
            txtgpstime.setValue(getMonthDayFromFullTime(tinfo.gpstime));
            txtreceivedtime.setValue(getMonthDayFromFullTime(tinfo.receivedtime));
            txtgpsvalid.setValue(getValidString(tinfo.gpsvalid));
            txtlatitude.setValue(tinfo.latitude);
            txtlongitude.setValue(tinfo.longitude);
            txtspeed.setValue(tinfo.speed);
            txtdirection.setValue(getDirectionString(tinfo.direction));
            //txtdirection.setValue(getDirectionString(tinfo.direction));
            //txtaltitude.setValue(tinfo.altitude);

        }

        function showStatusinPanelByRecord(record) {
            txtname.setValue(record.get("devicename"));
            txtgpstime.setValue(getMonthDayFromFullTime(record.get("gpstime")));
            txtreceivedtime.setValue(getMonthDayFromFullTime(record.get("receivedtime")));
            txtgpsvalid.setValue(getValidString(record.get("gpsavailable")));
            txtlatitude.setValue(record.get("latitude"));
            txtlongitude.setValue(record.get("longitude"));
            var speed= record.get("speed");
            //if (showmiles)
            //    speed = kilos2miles(speed);
            txtspeed.setValue(speed);
            txtdirection.setValue(getDirectionString(record.get("direction")));
            //txtaltitude.setValue(record.get("altitude"));
            var devicetype = record.get("devicetype");
            var journey = (record.get("journey") / 1000).toFixed(2);
            if (showmiles) {
                journey = kilos2miles(journey);
            }
            var rtime = formatTime(record.get("runtime"));
            txtjourney.setValue(journey);
            txtruntime.setValue(rtime);
            reloadUserDefineData(record);
            
            //show tracker extend info
            var i=0;
            for (t in record.json) {
               
                var isExtendSensor = true;
                var j=0;
                for(j=0;j<record.fields.items.length;j++){
                    if(t.toString() ==record.fields.items[j].name){
                        isExtendSensor = false;
                        break;
                    }
                }
                if (isExtendSensor) {
                    
                    var fname = t;
                    var tmp = new Object();
                    
                    if(fname =='01FF' || fname.indexOf('S_S_')>=0)
                        fname = _ConfigResource_Fuel;
                    tmp.propertyname = fname;
                   
//                    if(t == '01FF')
//                        tmp.propertyvalue = parseFloat(record.json[t])*100+"%";
//                    else
                    tmp.propertyvalue = record.json[t];
                    if(showfahrenheit){
                        if(fname != _ConfigResource_Fuel)//not fuel sensor,
                            tmp.propertyvalue = Celsius2Fahrenheit(parseFloat(tmp.propertyvalue));
                    }
                    var rr = new Ext.data.Record(tmp);
                    if (fname.length > 0) {
                        if(fname!="State")
                            userdefinestore.add(rr);
                    }
                   
                }
            }
            
            if (imap != null) {
               /*phu comment imap.geoCoder(record.get("latitude"), record.get("longitude"), function(address) {
                    var hasgsmlocation = record.get("hasgsmlocation");
                    var gpsValid = record.get("gpsavailable");
                    if (gpsValid == true) {
                        txtlocation.setValue("GPS "+_Alarm_Header_Location + ":" + address);
                    }
                    else {
                        if (hasgsmlocation) {
                            imap.geoCoder(record.get("gsmlatitude"), record.get("gsmlongitude"), function(gsmaddress) {
                                txtlocation.setValue(_TrackerMain_GSMBaseLocation + ':' + gsmaddress);
                            });
                        }
                        else {
                            txtlocation.setValue(_TrackerMain_GPSLastLocation + ':' + address);
                        }
                    }
                });
				*/
            }
        }

        function reloadUserDefineData(record) {
            userdefinestore.removeAll();

            var devicetype = record.get("devicetype");

            var itemGSMSignal = new Object();
            itemGSMSignal.propertyname = _TrackerMain_GSMSignal;
            itemGSMSignal.propertyvalue = record.get("gsmsignal");
            if (itemGSMSignal.propertyvalue > 0) {
                var rgsmsignal = new Ext.data.Record(itemGSMSignal);
                userdefinestore.add(rgsmsignal);
            }


            var itemSata = new Object();
            itemSata.propertyname = _TrackerMain_Satellites;
            itemSata.propertyvalue = record.get("satellites");
            if (itemSata.propertyvalue > 0) {
                var rsata = new Ext.data.Record(itemSata);
                userdefinestore.add(rsata);
            }

            var itemAltitude= new Object();
            itemAltitude.propertyname = _TrackerMain_Altitude;
            itemAltitude.propertyvalue = record.get("altitude");
            if (itemAltitude.propertyvalue > 0) {
                var rsata = new Ext.data.Record(itemAltitude);
                userdefinestore.add(rsata);
            }

            if (devicetype == EnumDeviceType.MVT600 || devicetype == EnumDeviceType.T1) {
                var itemObj = new Object();
                itemObj.propertyname = _TrackerMain_RFID;
                itemObj.propertyvalue = record.get("RFID");
                var rRFID = new Ext.data.Record(itemObj);
                userdefinestore.add(rRFID);
            }


            //User Define only use for VT
//            if (devicetype == EnumDeviceType.VT300 || devicetype == EnumDeviceType.VT310 || devicetype == EnumDeviceType.MVT100 || devicetype == EnumDeviceType.MVT340 || devicetype == EnumDeviceType.MVT380
//        || devicetype == EnumDeviceType.VT400 || devicetype == EnumDeviceType.MVT600) {
                //VT except VT300 has input output user define
                var len = locationfields.length;
                var i;

                for (i = fixfieldslength; i < locationfields.length; i++) {
                    var fname = locationfields[i].name;
                    var tmp = new Object();
                    tmp.propertyname = fname;
                    tmp.propertyvalue = record.get(fname);
                    var rr = new Ext.data.Record(tmp);
                    userdefinestore.add(rr);
                }

            //}

            /* var len = locationfields.length;
            var i;
            var obj = record.get("UserDefineList");
            for (i = 0; i < obj.length; i++) {
            var tmp = new Object();
            tmp.propertyname = obj[i].FieldName;
            tmp.propertyvalue = obj[i].Value;
        
    var rr = new Ext.data.Record(tmp);
            userdefinestore.add(rr);
            }*/

        }